﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DNA.Mvc.UI
{
    public class WidgetZoneBuilder : ViewComponentBuilder<WidgetZone, WidgetZoneBuilder>
    {
        public WidgetZoneBuilder(WidgetZone zone, ViewContext context, IViewDataContainer container) : base(zone, context, container) { }

        public WidgetZoneBuilder Content(Action template)
        {
            Component.Content = template;
            return this;
        }

        public WidgetZoneBuilder Content(Func<object, object> template)
        {
            Component.InlineContent = template;
            return this;
        }

        public override void Render()
        {
            _InitScripts();
            base.Render();
        }

        public override MvcHtmlString GetHtml()
        {
            _InitScripts();
            return base.GetHtml();
        }

        //[Microsoft.Practices.Unity.Dependency]
        //public WebSiteContext Context { get; set; }

        private void _InitScripts()
        {
            var isDesign = false;

            if (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["design"]))
            {
                bool.TryParse(HttpContext.Current.Request.QueryString["design"], out isDesign);
            }

            if (!isDesign)
            {
                //var instances =WebSiteContext.Current.DataContext.Widgets.Filter(w=>w.PageID==WebSiteContext.Current.Page.ID && w.ZoneID.Equals(Component.Id,StringComparison.OrdinalIgnoreCase) && w.IsExpanded);
                if (WebSiteContext.Current.Page != null && WebSiteContext.Current.Page.Widgets!=null)
                {
                    var instances = WebSiteContext.Current.Page.Widgets.Where(w => w.ZoneID.Equals(Component.Id, StringComparison.OrdinalIgnoreCase) && w.IsExpanded).OrderBy(w=>w.Pos);
                    Component.Title = "";
                    foreach (var instance in instances)
                    {
                        //if (instance.IsExpanded)
                        Component.Widgets.Add(new Widget()
                        {
                            Name = instance.ID.ToString(),
                            Model = instance,
                            Html = new HtmlHelper(this.Helper.ViewContext, this.Helper.ViewDataContainer)
                        });
                    }
                }
            }
        }
    }
}